package it.francescogabbrielli.android.solidalapp.actions;

import android.location.Location;
import android.util.Log;
import it.francescogabbrielli.android.solidalapp.Action;
import it.francescogabbrielli.android.solidalapp.Constants;
import it.francescogabbrielli.android.solidalapp.EndpointsUtils;
import it.francescogabbrielli.android.solidalapp.R;
import it.francescogabbrielli.android.solidalapp.SolidalApp;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.deviceendpoint.Deviceendpoint;
import it.francescogabbrielli.android.solidalapp.deviceendpoint.model.Device;

public class EndpointsInsertDevice extends Action {
	
	private Device device;

	@Override
	public void execute() throws Exception {
		
		String regId = app.getStatus().getGcmId();
		if (regId==null)
			return;
		
		Device newDevice = fillDevice(regId);
		Deviceendpoint endpoint = EndpointsUtils.buildEndpoint(Deviceendpoint.class);
		device = endpoint.insertDevice(newDevice).execute();
		setModel(device);
		Log.i(getClass().getSimpleName(), "Device inserted: "+device);
	}

	@Override
	public void onPostExecute() throws Exception {
		if(device!=null) {
			app.setData(DataKey.DEVICE, device);
			app.registerToServices();
		} else if(app.getData(DataKey.DEVICE)==null) {
			app.alert(context.getString(R.string.error_server, "Null device?"), true);
			Log.e(SolidalApp.TAG, "Unexpected null device");
		}
	}
	
	protected Device fillDevice(String regId) throws Exception {
		Device device = new Device();
		device.setRegistrationId(regId);
		return fillDevice(device);
	}
	
	protected Device fillDevice(Device device) throws Exception {
		int version = app.getPackageManager().getPackageInfo(
				app.getPackageName(), 0).versionCode;
		String info = android.os.Build.MANUFACTURER + " " + android.os.Build.PRODUCT;
		device
			.setTimestamp(System.currentTimeMillis())
			.setAppVersion(version)
			.setInformation(info)
			;
		
		// Location tracking
		Location location = (Location) app.getData(DataKey.ADDRESS_LOCATION);
		if (location!=null && !"NONE".equals(prefs.getString(Constants.PREF_NOTIFY, "NONE")))
			device.setLatitude(location.getLatitude()).setLongitude(
					location.getLongitude());
		
		return device;
	}
	
}
